package com.news.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.news.dao.BaseDao;
import com.news.dao.UserDao;
import com.news.entity.User;
import com.news.exception.UserBCZException;
import com.news.exception.UserPwdException;

public class UserDaoImpl extends BaseDao implements UserDao {

	@Override
	public int addUser(User u) {

		String sql = " INSERT INTO `user_table` (username,nickname,`from`,`password`,`level`)" + " VALUE('"
				+ u.getUsername() + "','" + u.getNickname() + "','" + u.getFrom() + "','" + u.getPassword() + "',"
				+ u.getLevel() + ") ";

		return super.update(sql);
	}

	@Override
	public int udpateUser(User u) {
		String sql = "update user_table set password ='" + u.getPassword() + "' where uid =" + u.getUid();

		return super.update(sql);
	}

	/**
	 * 通用查询方法
	 */

	public List<User> getUsers(String sql) {
		System.out.println(sql);
		List<User> userlist = new ArrayList<>();
		Connection con = getCon();
		Statement stmt = null;
		ResultSet rs = null;

		try {
			System.out.println("创建执行对象");
			stmt = con.createStatement();
			System.out.println("获取结果集");
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				User u = new User();
				u.setUid(rs.getInt("uid"));
				u.setUsername(rs.getString("username"));
				u.setNickname(rs.getString("nickname"));
				u.setPassword(rs.getString("password"));
				u.setFrom(rs.getString("from"));
				u.setLevel(rs.getInt("level"));
				u.setStatus(rs.getInt("status"));
				userlist.add(u);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(con, stmt, rs);
		}
		return userlist;
	}

	@Override
	// throws 是一种声明，表示，这个方法执行时，可能会出现异常的各类
	public User checkUser(User u) throws UserPwdException, UserBCZException {
		String sql = "select * from user_table where username='" + u.getUsername() + "'";
		List<User> list = getUsers(sql);
		User user = null;
		if (list.size() > 0) {
			user = list.get(0);
			if (u.getPassword().equals(user.getPassword())) {
				// 登录成功
				return user;
			} else {
				// 以下代码抛出了异常
				throw new UserPwdException();
			}
		} else {

			throw new UserBCZException();
		}

	}

	@Override
	public User getUserByuid(int uid) {
		String sql = "select * from user_table where uid =" + uid;
		List<User> list = getUsers(sql);
		if (list.size() > 0)
			return list.get(0);
		return null;
	}

	@Override
	public List<User> getAllUsers() {
		String sql = "select * from user_table";
		return getUsers(sql);
	}

}
